package cn.aishua.ui.main;

import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cn.aishua.R;
import cn.aishua.data.HotsDataParser;
import cn.aishua.ui.test.MyKakaTestJsonData;

public class HotOnesActivity
    extends Activity
{

    static final int STATE_PICS = 0;
    static final int STATE_WALL = 1;
    static final int MAX_INTERVAL = 60000 * 30;//30 mins
    static final int MSG_FETCH_DONE = 100;
    static final int MSG_DOWNLOAD_IMAGE_DONE = 200;

    private int STATE = -1;
    ImageView imageFunc;
    TextView textHeaderTitle;
    LinearLayout linearPics;
    LinearLayout linearWall;
    ProgressBar progressBar1;
    ListView listPics;

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.hotones );
        init();

    }

    OnClickListener imageFuncClickListener = new OnClickListener()
    {
        public void onClick( View v )
        {
            switch( STATE )
            {
                case STATE_PICS:
                    imageFunc.setImageResource( R.drawable.btn_func_pics );
                    textHeaderTitle.setText( "热门推荐" );
                    linearPics.setVisibility( View.GONE );
                    linearWall.setVisibility( View.VISIBLE );
                    STATE = STATE_WALL;
                    break;
                case STATE_WALL:
                    imageFunc.setImageResource( R.drawable.btn_func_wall );
                    textHeaderTitle.setText( "爱刷优惠" );
                    linearPics.setVisibility( View.VISIBLE );
                    linearWall.setVisibility( View.GONE );
                    STATE = STATE_PICS;
                    break;
            }
        }
    };

    private void init()
    {
        STATE = STATE_PICS;
        imageFunc = (ImageView) findViewById( R.id.imageFunc );
        imageFunc.setOnClickListener( imageFuncClickListener );
        textHeaderTitle = (TextView) findViewById( R.id.textHeaderTitle );
        linearPics = (LinearLayout) findViewById( R.id.linearPics );
        linearPics.setVisibility( View.VISIBLE );
        linearWall = (LinearLayout) findViewById( R.id.linearWall );
        linearWall.setVisibility( View.GONE );

        progressBar1 = (ProgressBar) findViewById( R.id.progressBar1 );
        progressBar1.setVisibility( View.GONE );

        listPics = (ListView) findViewById( R.id.listPics );
        listPics.setDividerHeight( 0 );
        fetch();
    }

    HotsDataParser data;

    Thread fetchThread = new Thread()
    {
        public void run()
        {
            try
            {
                //TODO
                Thread.sleep( 2000 );
                data = new HotsDataParser( MyKakaTestJsonData.HOTS_DATA );
                mHandler.obtainMessage( MSG_FETCH_DONE ).sendToTarget();
            }
            catch( InterruptedException e )
            {
                e.printStackTrace();
            }
        }
    };

    private void downloadImage( final ImageView v, final String urlString )
    {

        new Thread()
        {
            public void run()
            {
                try
                {
                    URL url = new URL( urlString );
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput( true );
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    SoftReference<Bitmap> s = new SoftReference<Bitmap>( BitmapFactory.decodeStream( is ) );
                    Object[] objs = { v, s.get() };
                    mHandler.obtainMessage( MSG_DOWNLOAD_IMAGE_DONE, objs ).sendToTarget();
                }
                catch( Exception e )
                {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    Handler mHandler = new Handler()
    {
        public void handleMessage( android.os.Message msg )
        {
            switch( msg.what )
            {
                case MSG_FETCH_DONE:
                    progressBar1.setVisibility( View.GONE );
                    imageFunc.setEnabled( true );
                    listPics.setAdapter( new ListPicsAdapter( HotOnesActivity.this ) );
                    break;
                case MSG_DOWNLOAD_IMAGE_DONE:
                    Object[] objs = (Object[]) msg.obj;
                    ( (ImageView) objs[0] ).setImageBitmap( (Bitmap) objs[1] );
                    break;
            }
        }
    };

    private void fetch()
    {
        fetchThread.start();
        progressBar1.setVisibility( View.VISIBLE );
        imageFunc.setEnabled( false );
    }

    class ListPicsAdapter
        extends BaseAdapter
    {

        Context mContext;

        class ColorTextPair
        {
            String color;
            String text;

            public ColorTextPair(String c, String t)
            {
                color = c;
                text = t;
            }
        }

        final ColorTextPair[] ctp = { new ColorTextPair( "#f3a448", "餐饮美食" ), new ColorTextPair( "#f37f62", "休闲娱乐" ),
                new ColorTextPair( "#e274a5", "超市商场" ), new ColorTextPair( "#67b3d3", "生活服务" ),
                new ColorTextPair( "#8bc763", "酒店旅游" ) };
        int ctp_pos = 0;

        public ListPicsAdapter(Context context)
        {
            mContext = context;
            data.pos = 0;
            ctp_pos = 0;
        }

        public int getCount()
        {
            return 8;
        }

        public Object getItem( int position )
        {
            return position;
        }

        public long getItemId( int position )
        {
            return position;
        }

        public View getView( int position, View convertView, ViewGroup parent )
        {
            View v = null;
            data.pos = quirk_pos[position];
            ctp_pos = quirk_ctp_pos[position];
            l( "position " + position + ", pos " + data.pos );
            if( selector( data.pos ) == R.layout.hots_list_item1 )
            {
                v = LayoutInflater.from( mContext ).inflate( R.layout.hots_list_item1, null );
                ( (TextView) v.findViewById( R.id.textView1 ) ).setText( data.vendors.get( data.pos ).name );
                downloadImage( (ImageView) v.findViewById( R.id.imageView1 ),
                    "http://hiphotos.baidu.com/pochacco_pp/pic/item/b10f840192014847728da500.jpg" );
                data.pos++;
                if( data.pos == data.count )
                    return v;

                ( (TextView) v.findViewById( R.id.textView2 ) ).setText( data.vendors.get( data.pos ).name );
                //				downloadImage((ImageView)v.findViewById(R.id.imageView2), data.vendors.get(data.pos).pic_url);
                data.pos++;
                if( data.pos == data.count )
                    return v;

                ( (TextView) v.findViewById( R.id.textView3 ) ).setText( data.vendors.get( data.pos ).name );
                //				downloadImage((ImageView)v.findViewById(R.id.imageView3), data.vendors.get(data.pos).pic_url);
                data.pos++;
                if( data.pos == data.count )
                    return v;
            }
            else if( selector( data.pos ) == R.layout.hots_list_item2
                || selector( data.pos ) == R.layout.hots_list_item3 )
            {
                v = LayoutInflater.from( mContext ).inflate( selector( data.pos ), null );
                ( (TextView) v.findViewById( R.id.textView1 ) ).setText( data.vendors.get( data.pos ).name );
                //				downloadImage((ImageView)v.findViewById(R.id.imageView1), data.vendors.get(data.pos).pic_url);
                data.pos++;
                if( data.pos == data.count )
                    return v;

                ( (TextView) v.findViewById( R.id.textView2 ) ).setText( ctp[ctp_pos].text );
                ( (TextView) v.findViewById( R.id.textView2 ) ).setBackgroundColor( Color
                    .parseColor( ctp[ctp_pos].color ) );

                ( (TextView) v.findViewById( R.id.textView3 ) ).setText( "共156家商户" );
                ( (TextView) v.findViewById( R.id.textView3 ) ).setBackgroundColor( Color
                    .parseColor( ctp[ctp_pos].color ) );
                ctp_pos++;
            }
            else if( selector( data.pos ) == R.layout.hots_list_item4 )
            {
                v = LayoutInflater.from( mContext ).inflate( R.layout.hots_list_item4, null );
                ( (TextView) v.findViewById( R.id.textView1 ) ).setText( data.vendors.get( data.pos ).name );
                //				downloadImage((ImageView)v.findViewById(R.id.imageView1), data.vendors.get(data.pos).pic_url);
                data.pos++;
                if( data.pos == data.count )
                    return v;

                ( (TextView) v.findViewById( R.id.textView2 ) ).setText( data.vendors.get( data.pos ).name );
                //				downloadImage((ImageView)v.findViewById(R.id.imageView2), data.vendors.get(data.pos).pic_url);
                data.pos++;
                if( data.pos == data.count )
                    return v;

                ( (TextView) v.findViewById( R.id.textView3 ) ).setText( data.vendors.get( data.pos ).name );
                //				downloadImage((ImageView)v.findViewById(R.id.imageView3), data.vendors.get(data.pos).pic_url);
                data.pos++;
                if( data.pos == data.count )
                    return v;
            }
            l( "return " + v );
            return v;
        }

        int[] quirk_pos = { 0, 3, 4, 7, 8, 11, 12, 13, 16, 17 };
        int[] quirk_ctp_pos = { 0, 0, 0, 1, 1, 2, 3, 3, 4, 4 };

        private int selector( int pos )
        {
            int layout = -1;
            switch( pos )
            {
                case 0:
                    layout = R.layout.hots_list_item1;
                    break;
                case 3:
                    layout = R.layout.hots_list_item2;
                    break;
                case 4:
                    layout = R.layout.hots_list_item4;
                    break;
                case 7:
                    layout = R.layout.hots_list_item3;
                    break;
                case 8:
                    layout = R.layout.hots_list_item1;
                    break;
                case 11:
                    layout = R.layout.hots_list_item2;
                    break;
                case 12:
                    layout = R.layout.hots_list_item3;
                    break;
                case 13:
                    layout = R.layout.hots_list_item4;
                    break;
                case 16:
                    layout = R.layout.hots_list_item2;
                    break;
                case 17:
                    layout = R.layout.hots_list_item1;
                    break;
            }

            return layout;
        }

    }

    //-----------------------------------------
    //	private void checkFetch() {
    //		SharedPreferences sp = getSharedPreferences("hots_get", 0);
    //		long when = sp.getLong("when", -1);
    //		if(when != -1){
    //			boolean done = sp.getBoolean("done", false);
    //			if(done){
    //				long distance = System.currentTimeMillis() - when;
    //				if(distance > MAX_INTERVAL){
    //					fetch();
    //				}else{
    //					//fetch from local
    //					fetchLocal();
    //				}
    //			}else{
    //				fetch();
    //			}
    //		}else{
    //			//Start to fetch and update time
    //			fetch();
    //		}
    //	}

    //    private void fetchLocal()
    //    {
    //
    //    }

    void l( String s )
    {
        android.util.Log.d( "test", s );
    }

}
